package com.cnswhy.cloud.server.app.controller.customer;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cnswhy.cloud.common.core.utils.BeanPlusUtil;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.app.controller.BaseController;
import com.cnswhy.cloud.server.core.constant.RedisConstant;
import com.cnswhy.cloud.server.core.dto.CustomerAlipaySaveDTO;
import com.cnswhy.cloud.server.core.entity.Customer;
import com.cnswhy.cloud.server.core.entity.CustomerAlipay;
import com.cnswhy.cloud.server.core.oem.OemService;
import com.cnswhy.cloud.server.core.query.QueryGenerator;
import com.cnswhy.cloud.server.core.service.customer.CustomerAlipayService;
import com.cnswhy.cloud.server.core.vo.RespVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@Api(tags = "客户支付宝控制层")
@RequestMapping("/alipayAccount")
@Slf4j
public class CustomerAlipayController extends BaseController {

    @Autowired
    private CustomerAlipayService customerAlipayService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private OemService oemService;

    @ApiOperation(value = "查询支付宝账号", httpMethod = "POST")
    @ApiParam(name = "bo", value = "客户支付宝账号bo对象", required = true)
    @RequestMapping("/ajaxPageData")
    @ResponseBody
    public RespVo ajaxPageData(CustomerAlipay customerAlipay,
                               @RequestParam(name = "currentPage", defaultValue = "1") Integer currentPage,
                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest request) {
        log.info("查询支付宝账号：{} {} {}", JSON.toJSONString(customerAlipay), currentPage, pageSize);

        RespVo vo = new RespVo();
        try {
            Customer loginCustomer = getLoginCustomer( request);
            customerAlipay.setCustomerId(loginCustomer.getId());
            QueryWrapper<CustomerAlipay> queryWrapper = QueryGenerator.initQueryWrapper(customerAlipay);
            queryWrapper.orderByDesc("create_time");
            Page<CustomerAlipay> page = new Page<>(currentPage, pageSize);
            IPage<CustomerAlipay> pageList = customerAlipayService.page(page, queryWrapper);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setResult(pageList);
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("查询支付宝账号失败");
            log.error("查询支付宝账号失败", e);
        }
        return vo;
    }

    @ApiOperation(value = "保存支付宝账号", httpMethod = "POST")
    @ApiParam(name = "account", value = "支付宝账号实体", required = true)
    @RequestMapping("/saveData")
    @ResponseBody
    public RespVo saveData(CustomerAlipaySaveDTO account, HttpServletRequest request) {
        log.info("保存支付宝账号：{}", JSON.toJSONString(account));
        RespVo vo = new RespVo();
        try {
            /**/
            if (StringUtils.isBlank(account.getSysCode())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("验证码为空");
                return vo;
            }
            if (!checkVerifyCode(account.getMobile(), account.getSysCode())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("验证码错误");
                return vo;
            }
            if (StringUtils.isBlank(account.getRealName())) {
                vo.setCode(RespVo.VALIDATE_ERROR);
                vo.setMessage("姓名为空");
                return vo;
            }
            Customer loginCustomer = getLoginCustomer( request);
            //强制同名提现
            if(oemService.isLeyoutuan()){
                if (StringUtils.isBlank(loginCustomer.getVerifyStatus())) {
                    if (!(loginCustomer.getVerifyStatus().equals("1"))) {
                        vo.setCode(RespVo.VALIDATE_ERROR);
                        vo.setMessage("未实名不能添加支付宝！");
                        return vo;
                    }
                }
                if (!(account.getRealName().equals(loginCustomer.getVerifyName()))) {
                    vo.setCode(RespVo.VALIDATE_ERROR);
                    vo.setMessage("只能添加本人的支付宝！");
                    return vo;
                }
            }

            List<CustomerAlipay> queryPage = customerAlipayService.getCustomerAlipayList(loginCustomer.getId());
            if (queryPage != null && queryPage.size() >= 5) {
                vo.setCode(RespVo.CODE_ERROR);
                vo.setMessage("一个账号最多绑定五个支付宝账号");
                return vo;
            }
            account.setCustomerId(loginCustomer.getId());
            CustomerAlipay customerAlipay = BeanPlusUtil.toBean(account, CustomerAlipay.class);
            customerAlipayService.save(customerAlipay);
            vo.setCode(RespVo.CODE_SUCCESS);
            vo.setMessage("保存成功");
        } catch (Exception e) {
            vo.setCode(RespVo.CODE_ERROR);
            vo.setMessage("保存失败");
            log.error("保存支付宝账号失败", e);
        }
        return vo;
    }

    public boolean checkVerifyCode(String mobile, String verifyCode) {
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(verifyCode)) {
            return false;
        }

        String redisVerifyCode = (String) redisService.get(RedisConstant.PASS_VERIFY_CODE_REDIS_KEY + mobile);
        if (StringUtils.isBlank(redisVerifyCode) || !verifyCode.equals(redisVerifyCode)) {
            return false;
        }

        return true;
    }
}
